﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
using UTSDAL.LINQSQL.DAO;
using UTSDAL.LINQSQL.Model;


namespace UTS.Controls
{
    [
        DefaultProperty("Text"),
        ToolboxData("<{0}:ModuleDropDownList runat=\"server\"> </{0}:ModuleDropDownList>")
    ]
    public class ModuleDropDownList : System.Web.UI.WebControls.DropDownList
    {

        private ModuleDAO moduleDAO = new ModuleDAO();

        private void init()
        {

            this.DataSource = moduleDAO.selectAll();
            this.DataBind();
            DropDownUtils.addDefaultLabel(this, "Select a Module");
            this.DataTextField = "ModuleName";
            this.DataValueField = "ModuleId";
        }

        // this method bypasses non post back requests by ajax
        public void reload()
        {
            init();
        }
        
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                init();
            }
        }


        private Module module;

        public Module Module
        {
            get {
                if (StringUtils.isValidGuid(this.SelectedValue.ToString()))
                {
                    module = moduleDAO.findById(new Guid(this.SelectedValue.ToString()));
                }
                return module; 
            }
            set { 
                module = value;
                if (module != null)
                {
                    this.SelectedValue = module.ModuleId.ToString();
                }
            }
        }


    }
}